/*
 * MainFrame.java
 *
 * Created on 5 de Dezembro de 2007, 16:36
 */
package madsgtdinterface;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import thunderbirdgtd.GTDParent;
import thunderbirdgtd.entities.Action;
import thunderbirdgtd.entities.BaseActionOrProject;
import thunderbirdgtd.entities.Project;
import thunderbirdgtd.entities.Tag;
import thunderbirdgtd.global.XmlUtil;

/**
 *
 * @author  trmfreitas
 */
public class MainFrame extends javax.swing.JFrame {

    GTDParent gtdParent;
    ProjectModel pm;
    JPopupMenu menuDireito;

    /** Creates new form MainFrame */
    public MainFrame() {
        try {
            gtdParent = new GTDParent();


            initComponents();
            jTree1.setShowsRootHandles(true);
            jTree1.setRootVisible(false);
            new AlarmClock(gtdParent, this);
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new JTree(pm);
        bt_delete = new javax.swing.JButton();
        bt_addprj = new javax.swing.JButton();
        bt_addact = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuSaveItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MADS GTD");

        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        bt_delete.setText("Delete");
        bt_delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_deleteActionPerformed(evt);
            }
        });

        bt_addprj.setText("Add Project");
        bt_addprj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_addprjActionPerformed(evt);
            }
        });

        bt_addact.setText("Add Action");
        bt_addact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_addactActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(bt_delete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                        .addComponent(bt_addprj)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bt_addact)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_delete)
                    .addComponent(bt_addact)
                    .addComponent(bt_addprj)))
        );

        jMenu1.setText("File");

        jMenuItem1.setText("Open...");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuSaveItem.setText("Save...");
        jMenuSaveItem.setEnabled(false);
        jMenuSaveItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuSaveItemActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuSaveItem);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
        if (evt.getClickCount() == 2) {
            if (jTree1.getSelectionPath()!=null && jTree1.getSelectionPath().getLastPathComponent() instanceof Action) {
                TaskView tv = new TaskView((Action) jTree1.getSelectionPath().getLastPathComponent(), this);
                tv.setVisible(true);
            }
        }        
    }//GEN-LAST:event_jTree1MouseClicked

    private void bt_deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_deleteActionPerformed
       if(jTree1.getSelectionPath()==null)
           return;
       BaseActionOrProject baop = (BaseActionOrProject) jTree1.getSelectionPath().getLastPathComponent();
       if (baop instanceof Action){
           gtdParent.removeAction((Action) baop); 
           jTree1.setModel(new ProjectModel(gtdParent));
       }
       if (baop instanceof Project){
           gtdParent.removeProject((Project) baop);
           jTree1.setModel(new ProjectModel(gtdParent));
           if(gtdParent.projects.size() == 0)
               this.setMenuItemSaveEnabled(false);
       }
       
}//GEN-LAST:event_bt_deleteActionPerformed

    private void bt_addprjActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_addprjActionPerformed
        if (jTree1.getSelectionPath()!=null && jTree1.getSelectionPath().getLastPathComponent() instanceof Project) {
                AddProjects ap = new AddProjects(this, true, gtdParent, (Project)jTree1.getSelectionPath().getLastPathComponent() );
        ap.setVisible(true); 
        }
        else{
            AddProjects ap = new AddProjects(this, true, gtdParent);
            ap.setVisible(true);            
        }        
}//GEN-LAST:event_bt_addprjActionPerformed

    private void bt_addactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_addactActionPerformed
        if (jTree1.getSelectionPath()!=null && jTree1.getSelectionPath().getLastPathComponent() instanceof Project)  {
            AddAction actionGUI = new AddAction(this, (Project)jTree1.getSelectionPath().getLastPathComponent());
            actionGUI.setVisible(true);
        }
    }//GEN-LAST:event_bt_addactActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

        //open from file
        //Create a file chooser

        final JFileChooser fc = new JFileChooser();
                fc.putClientProperty("FileChooser.useShellFolder", Boolean.FALSE);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setAcceptAllFileFilterUsed(false);
        int returnVal = fc.showOpenDialog(this);
        File file = fc.getSelectedFile();

        if(file==null)
            return;
        
        try {            
            XmlUtil.openAll(file.getAbsolutePath(), gtdParent);
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        jTree1.setModel(new ProjectModel(gtdParent));
        if(gtdParent.projects.size()>0)
            this.setMenuItemSaveEnabled(true);
    //
    // jTree1.setRootVisible(true);
    //jTree1.fire
        
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuSaveItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSaveItemActionPerformed
        
        final JFileChooser fc = new JFileChooser();
        fc.putClientProperty("FileChooser.useShellFolder", Boolean.FALSE);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setAcceptAllFileFilterUsed(false);
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                File file = fc.getSelectedFile();
                XmlUtil.saveAll(file.getAbsolutePath(), gtdParent);
            } catch (Exception ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}//GEN-LAST:event_jMenuSaveItemActionPerformed

    public void setMenuItemSaveEnabled(boolean value){
        jMenuSaveItem.setEnabled(value);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_addact;
    private javax.swing.JButton bt_addprj;
    private javax.swing.JButton bt_delete;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuSaveItem;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
}
